package com.combetter.changxing.viewmodel;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.databinding.ObservableField;
import android.support.annotation.NonNull;
import android.view.View;

import com.combetter.changxing.MyApp;
import com.combetter.changxing.bluetooth.FacilityClient2;
import com.combetter.changxing.db.AppDatabase;
import com.combetter.changxing.db.entity.Collect;
import com.combetter.changxing.model.Smoke;
import com.combetter.changxing.net.service.APIService;
import com.combetter.changxing.ui.activity.MineCollectActivity;
import com.combetter.changxing.ui.activity.TestAuthActivity;
import com.combetter.changxing.ui.dialog.LoadingDialog;
import com.combetter.changxing.util.Check;
import com.combetter.changxing.util.LogUtil;
import com.combetter.changxing.util.ToastUtils;
import com.combetter.changxing.viewmodel.base.BaseViewModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by 深圳唐龙飞讯科技有限公司 on 2018/6/7.
 */

public class HomeViewModel extends BaseViewModel {
    //品牌
    public ObservableField<String> brand = new ObservableField<>("暂无数据");
    //型号
    public ObservableField<String> model = new ObservableField<>("暂无数据");

    public HomeViewModel(@NonNull Application application) {
        super(application);
    }


    public void testAuth(View v) {
        v.getContext().startActivity(new Intent(v.getContext(), TestAuthActivity.class));
    }

    /**
     * 获取当前品牌香烟
     */
    public void insertSmoke() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("uid", MyApp.getInstance().getUserInfo().getUid());
        LogUtil.e("获取当前品牌香烟参数：", map);
        mHttpRequest.createService(APIService.class)
                .selectUidType(map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(httpResult -> {
                    LogUtil.e("获取当前品牌香烟返回：", httpResult);
                    if (httpResult.getCode() == 200) {
                        Smoke smoke = httpResult.getData();
                        int position = smoke.getGoodsName().indexOf("_");
                        if (position != -1) {
                            String brand2 = smoke.getGoodsName().substring(0, position);
                            String model2 = smoke.getGoodsName().substring(position + 1, smoke.getGoodsName().length());
                            brand.set(brand2);
                            model.set(model2);
                        }
//                        if (!Check.isEmpty(smoke.getYid())) {
//                            int yid1 = Integer.parseInt(smoke.getYid().substring(0, 2));
//                            int yid2 = Integer.parseInt(smoke.getYid().substring(2, 4));
//                            byte[] data = new byte[]{(byte) yid1, (byte) yid2};
//                            FacilityClient.getClient().cutCmoke(data);
//                        }
                        if (!Check.isEmpty(smoke.getSindex()) && !Check.isEmpty(smoke.getTrademark())) {
                            int yid1 = Integer.parseInt(smoke.getSindex().substring(0, 2));
                            int yid2 = Integer.parseInt(smoke.getSindex().substring(2, 4));
                            byte[] data0 = new byte[]{(byte) yid1, (byte) yid2};
//                            byte[] data = ByteUtils.addBytes(data0,smoke.getTrademark().getBytes());
                            LogUtil.e("----: getTrademark: " + smoke.getTrademark());//Marlboro_Balance
//                            LogUtil.e("----: bef: "+ByteUtils.printBytes(data));
                            FacilityClient2.getClient().cutCmoke(data0, smoke.getTrademark().getBytes());
                        }
                    } else {
                        ToastUtils.error(httpResult.getMsg());
                    }
                });
    }


    /**
     * 扫一扫添加收藏
     *
     * @param code
     */
    public void selectSmokeMessage(Context context, String code) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("uid", MyApp.getInstance().getUserInfo().getUid());
        map.put("code", code);
        LoadingDialog dialog = new LoadingDialog(context);
        dialog.show();
        LogUtil.e("扫一扫添加收藏参数：", map);
        mHttpRequest.createService(APIService.class)
                .selectSmokeMessage(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnError(throwable -> dialog.dismiss())
                .subscribe(httpResult -> {
                    dialog.dismiss();
                    LogUtil.e("扫一扫添加收藏返回：", httpResult);
                    if (httpResult.getCode() == 200) {
                        Smoke smoke = httpResult.getData();
                        int position = smoke.getGoodsName().indexOf("_");
                        if (position != -1) {
                            String brand2 = smoke.getGoodsName().substring(0, position);
                            String model2 = smoke.getGoodsName().substring(position + 1, smoke.getGoodsName().length());
                            brand.set(brand2);
                            model.set(model2);
                        }
                        dealData(smoke);
                        if (!Check.isEmpty(smoke.getSindex()) && !Check.isEmpty(smoke.getTrademark())) {
                            int yid1 = Integer.parseInt(smoke.getSindex().substring(0, 2));
                            int yid2 = Integer.parseInt(smoke.getSindex().substring(2, 4));
                            byte[] data0 = new byte[]{(byte) yid1, (byte) yid2};
//                            byte[] data = ByteUtils.addBytes(data0,smoke.getTrademark().getBytes());
//                            LogUtil.e("----: bef: "+ByteUtils.printBytes(smoke.getTrademark().getBytes()));
//                            LogUtil.e("----: bef: "+ByteUtils.printBytes(data));
                            FacilityClient2.getClient().cutCmoke(data0, smoke.getTrademark().getBytes());
                        }
                    } else {
                        ToastUtils.error(httpResult.getMsg());
                    }
                });
    }


    public void dealData(Smoke smoke) {
        boolean isFlag = false;
        AppDatabase database = MyApp.getInstance().getDatabase();
        List<Collect> list = database.collectDao().getCollectInfoList();
        Collect newCollect = new Collect();
        newCollect.setCode(smoke.getCodes());
        newCollect.setSindex(smoke.getSindex());
        newCollect.setGoodsName(smoke.getGoodsName());
        newCollect.setType(smoke.getType());
        newCollect.setMuid(smoke.getMuid());
        newCollect.setTrademark(smoke.getTrademark());
        newCollect.setSelectCurrent(1);

        if (database.collectDao() != null && list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getCode().equals(smoke.getCodes())) {
                    list.get(i).setSelectCurrent(1);
                    isFlag = true;
                    break;
                } else {
                    isFlag = false;
                    list.get(i).setSelectCurrent(2);
                }
            }
            if (!isFlag) {
                list.add(newCollect);
            }
        } else {
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(newCollect);
        }
        MyApp.getInstance().getDatabase().collectDao().deleteAll();
        for (Collect collect : list) {
            MyApp.getInstance().getDatabase().collectDao().insertSingle(collect);
        }
    }

    /**
     * 发送香烟抽吸数据
     *
     * @param map
     */
    public void addSmokeCount(Map<String, String> map) {
        LogUtil.e("发送香烟抽吸数据参数：", map);
        mHttpRequest.createService(APIService.class)
                .addSmokeCount(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(httpResult -> {
                    LogUtil.e("发送香烟抽吸数据返回：", httpResult);
                    if (httpResult.getCode() == 200) {
                        FacilityClient2.getClient().sendSuccess();
                        LogUtil.e("发送香烟抽吸数据成功");
                    } else {
                        ToastUtils.error(httpResult.getMsg());
                    }
                });
    }

    /**
     * 跳转到收藏列表
     */
    public void collect(View view) {
        startActivity(MineCollectActivity.class);
    }
}
